package pro2_transport.P2_chat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;

/**
 * @program: netty
 * @description:
 * @author: zy
 * @create: 2025-08-28 14:42
 */
public class ChatClient {
    private Selector selector;
    private SocketChannel client;
    private String username;

    public ChatClient(String host, int port, String username) throws IOException {
        this.username = username;
        selector = Selector.open();
        client = SocketChannel.open(new InetSocketAddress(host, port));
        client.configureBlocking(false);
        client.register(selector, SelectionKey.OP_READ);
        System.out.println("已连接到聊天室服务器");
    }

    // 启动客户端
    public void start() {
        // 1. 另起线程负责监听服务端消息
        new Thread(this::receiveMessage).start();

        // 2. 主线程负责发送消息
        try (Scanner scanner = new Scanner(System.in)) {
            while (scanner.hasNextLine()) {
                String msg = scanner.nextLine();
                client.write(ByteBuffer.wrap((username + ": " + msg).getBytes()));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 监听服务端转发的消息
    private void receiveMessage() {
        try {
            while (true) {
                selector.select();  //阻塞 ,等 待事件发生
                Iterator<SelectionKey> keys = selector.selectedKeys().iterator();
                while (keys.hasNext()) {
                    SelectionKey key = keys.next();
                    keys.remove();

                    if (key.isReadable()) {
                        SocketChannel sc = (SocketChannel) key.channel();
                        ByteBuffer buffer = ByteBuffer.allocate(1024);
                        int read = sc.read(buffer);  //读数据到缓冲，指针就会移动读取的数据的末尾
                        if (read > 0) {
                            buffer.flip();  //  将指针移动到开头，准备读取数据
                            System.out.println(new String(buffer.array(), 0, buffer.limit()));
                        }
                    }
                }
            }
        } catch (IOException e) {
            System.out.println("服务器已关闭");
        }
    }

    public static void main(String[] args) throws IOException {
        ChatClient client = new ChatClient("127.0.0.1", 9999, "用户B");
        client.start();
    }
}
